package org.whatever.aha.zjut.platform.service;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.auth.COSSigner;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.model.GeneratePresignedUrlRequest;
import com.qcloud.cos.region.Region;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.whatever.aha.zjut.base.config.TencentCosConfig;
import org.whatever.aha.zjut.base.util.EncryptUtil;
import org.whatever.aha.zjut.base.util.TimeUtil;
import org.whatever.aha.zjut.platform.vo.CosPolicyVo;
import org.whatever.aha.zjut.platform.vo.CosPostPolicyVo;

import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.qcloud.cos.demo.BucketRefererDemo.bucketName;
import static com.qcloud.cos.demo.BucketRefererDemo.cosClient;

/**
 * @author Vc
 * @version 1.0
 * @Desc
 * @date 2021/10/07 21:56
 */
@Service
@RequiredArgsConstructor
public class TencentCosService {
    final TencentCosConfig tencentCosConfig;

    /**
     * 生成一个上传签名
     *
     * @param fileName  文件在存储桶中的路径
     * @return
     */
    public CosPolicyVo signPut(String fileName){
//        COSCredentials cred = new BasicCOSCredentials(tencentCosConfig.getSecretId(), tencentCosConfig.getSecretKey());
//        COSSigner signer = new COSSigner();
//        Date expiration = new Date(System.currentTimeMillis() + tencentCosConfig.getExpireTime() * 1000L);
//
//        // 填写本次请求的 header。Host 头部会自动补全，只需填入其他头部
//        Map<String, String> headers = new HashMap<String,String>();
//        // 填写本次请求的 params。
//        Map<String, String> params = new HashMap<String,String>();
//
//        String sign = signer.buildAuthorizationStr(HttpMethodName.PUT, fileName, headers, params, cred, expiration);

        Date expiration = new Date(System.currentTimeMillis() + tencentCosConfig.getExpireTime() * 1000L);

        // 填写本次请求的 header。Host 头部会自动补全，只需填入其他头部
        Map<String, String> headers = new HashMap<String,String>();
        // 填写本次请求的 params。
        Map<String, String> params = new HashMap<String,String>();

        URL url = tencentCosConfig.cosClient().generatePresignedUrl(tencentCosConfig.getResourceBucketName(), fileName, expiration, HttpMethodName.PUT, headers, params);
        System.out.println(url.toString());

        CosPolicyVo cosPolicyVo = new CosPolicyVo();
        cosPolicyVo.setRegion(tencentCosConfig.getRegion());
        cosPolicyVo.setSign(url.toString());
        cosPolicyVo.setFilename(fileName);
        cosPolicyVo.setExpire(expiration.getTime());
        return cosPolicyVo;
    }

    /**
     * 生成一个下载签名
     *
     * @param fileName
     * @return
     */
    public CosPolicyVo signDownload(String fileName){
//        COSCredentials cred = new BasicCOSCredentials(tencentCosConfig.getSecretId(), tencentCosConfig.getSecretKey());
//        COSSigner signer = new COSSigner();
//        Date expiration = new Date(System.currentTimeMillis() + tencentCosConfig.getExpireTime() * 1000L);
//
//        Map<String, String> headers = new HashMap<String,String>();
//        Map<String, String> params = new HashMap<String,String>();
//
//        String sign = signer.buildAuthorizationStr(HttpMethodName.GET, fileName, headers, params, cred, expiration);



        GeneratePresignedUrlRequest req =
                new GeneratePresignedUrlRequest(tencentCosConfig.getResourceBucketName(), fileName, HttpMethodName.GET);

        Date expiration = new Date(System.currentTimeMillis() + tencentCosConfig.getExpireTime() * 1000L);
        req.setExpiration(expiration);

//// 填写本次请求的参数
//        req.addRequestParameter("param1", "value1");
//// 填写本次请求的头部。Host 头部会自动补全，不需要填写
//        req.putCustomRequestHeader("header1", "value1");

        URL url = tencentCosConfig.cosClient().generatePresignedUrl(req);

        CosPolicyVo cosPolicyVo = new CosPolicyVo();
        cosPolicyVo.setRegion(tencentCosConfig.getRegion());
        cosPolicyVo.setSign(url.toString());
        cosPolicyVo.setFilename(fileName);
        cosPolicyVo.setExpire(expiration.getTime());
        return cosPolicyVo;
    }

    /**
     * 生成一个删除签名
     *
     * @param fileName
     * @return
     */
    public CosPolicyVo signDelete(String fileName){
        COSCredentials cred = new BasicCOSCredentials(tencentCosConfig.getSecretId(), tencentCosConfig.getSecretKey());
        COSSigner signer = new COSSigner();
        Date expiration = new Date(System.currentTimeMillis() + tencentCosConfig.getExpireTime() * 1000L);


        Map<String, String> headers = new HashMap<String,String>();
        Map<String, String> params = new HashMap<String,String>();

        String sign = signer.buildAuthorizationStr(HttpMethodName.DELETE, fileName, headers, params, cred, expiration);

        CosPolicyVo cosPolicyVo = new CosPolicyVo();
        cosPolicyVo.setRegion(tencentCosConfig.getRegion());
        cosPolicyVo.setSign(sign);
        cosPolicyVo.setFilename(fileName);
        cosPolicyVo.setExpire(expiration.getTime());
        return cosPolicyVo;
    }

    /**
     * 直接删除cos文件
     *
     * @param fileName
     * @return
     */
    public void deleteCos(String fileName){
        cosClient.deleteObject(tencentCosConfig.getResourceBucketName(), fileName);
    }

    /**
     * 上传信息
     *
     * @param filename
     * @return
     */
    public CosPostPolicyVo signPostAuthorization(String filename) {
        COSSigner cosSigner = new COSSigner();
        long now = System.currentTimeMillis();
        long startTimestamp = now / 1000L;
        long endTimestamp = startTimestamp + tencentCosConfig.getExpireTime();
        String keyTime = startTimestamp + ";" + endTimestamp;
        String policy = "{\n" +
                "    \"expiration\": \"" + TimeUtil.getISO8601Timestamp(endTimestamp * 1000L) + "\",\n" +
                "    \"conditions\": [\n" +
                "        { \"bucket\": \"" + tencentCosConfig.getResourceBucketName() + "\" },\n" +
                "        { \"key\": \"" + filename + "\" },\n" +
                "        { \"q-sign-algorithm\": \"sha1\" },\n" +
                "        { \"q-ak\": \"" + tencentCosConfig.getSecretId() + "\" },\n" +
                "        { \"q-sign-time\":\"" + keyTime + "\" }\n" +
                "    ]\n" +
                "}";
        String encodedPolicy = EncryptUtil.toBase64String(policy.getBytes());
        String signature = cosSigner.buildPostObjectSignature(tencentCosConfig.getSecretKey(), keyTime, policy);
        CosPostPolicyVo cosPostPolicyVo = new CosPostPolicyVo();
        cosPostPolicyVo.setRegion(tencentCosConfig.getRegion());
        cosPostPolicyVo.setBucketName(tencentCosConfig.getResourceBucketName());
        cosPostPolicyVo.setKeyTime(keyTime);
        cosPostPolicyVo.setPolicy(encodedPolicy);
        cosPostPolicyVo.setSignature(signature);
        cosPostPolicyVo.setSecretId(tencentCosConfig.getSecretId());
        cosPostPolicyVo.setFilename(filename);
        return cosPostPolicyVo;
    }


}
